package org.soma.sso.core.filter;


import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.soma.sso.core.store.CookieStore;
import org.soma.sso.core.utils.HttpUtils;

import com.alibaba.fastjson.JSONObject;



public class SomaSsoFilter extends HttpServlet implements Filter {

	/**
	 * serialVersionUID
	 */
	private static final long serialVersionUID = 5716474080011059081L;
	public static Logger logger = LoggerFactory.getLogger(SomaSsoFilter.class);

	private String SSO_SERVER_URL;
	private String SSO_SERVER_VERIFY_URL;

	public void init(FilterConfig filterConfig) throws ServletException {
		String contextPath =filterConfig.getServletContext().getContextPath();
		SSO_SERVER_URL = filterConfig.getInitParameter("SSO_SERVER_URL");
		SSO_SERVER_VERIFY_URL = filterConfig.getInitParameter("SSO_SERVER_VERIFY_URL");
		if (StringUtils.isBlank(SSO_SERVER_URL)) {
			logger.error("SSO_SERVER_URL is null.");
		}else{
			//SSO_SERVER_URL
		}
		if (StringUtils.isBlank(SSO_SERVER_VERIFY_URL)) {
			logger.error("SSO_SERVER_VERIFY_URL is null.");
		}
	}

	public void doFilter(ServletRequest servletRequest,
			ServletResponse servletResponse, FilterChain chain)
		throws IOException, ServletException {
			HttpServletRequest request = (HttpServletRequest) servletRequest;
			HttpServletResponse response = (HttpServletResponse) servletResponse;
			String token = request.getParameter("token");
			String callbackURL = request.getParameter("callbackURL");
			String cookieSessionId =CookieStore.getSessionIdByCookie(request);
			String buildCallbackURL = request.getRequestURL().toString();
		try{
			if(StringUtils.isNotBlank(token)){
				  List<NameValuePair> params = new ArrayList<NameValuePair>();
		          params.add(new BasicNameValuePair("token", token));
				  String verifyToken= HttpUtils.sendPost(SSO_SERVER_VERIFY_URL, params);
				  JSONObject jsonObject = JSONObject.parseObject(verifyToken);
				  String resultObj =jsonObject.getString("resultObj");
				  if(verifyToken!=null && resultObj!=null && resultObj.equals("true")){//返回为空时表示当前登陆已经失效
					  chain.doFilter(request, response);
		          }else{
		        	  //跳转至sso认证中心
						 StringBuilder url = new StringBuilder();
						 url.append(SSO_SERVER_URL).append("?callbackURL=").append(buildCallbackURL);
						 response.sendRedirect(url.toString());
		          }
				 return;
			}else{
				 if(StringUtils.isNotBlank(cookieSessionId)){
					 List<NameValuePair> params = new ArrayList<NameValuePair>();
			          params.add(new BasicNameValuePair("token", cookieSessionId));
					  String verifyToken= HttpUtils.sendPost(SSO_SERVER_VERIFY_URL, params);
					  JSONObject jsonObject = JSONObject.parseObject(verifyToken);
					  String resultObj =jsonObject.getString("resultObj");
					  if(verifyToken!=null && resultObj!=null && resultObj.equals("true")){//返回为空时表示当前登陆已经失效
						  chain.doFilter(request, response);
			          }
				 }
				 //跳转至sso认证中心
				 StringBuilder url = new StringBuilder();
				 url.append(SSO_SERVER_URL).append("?callbackURL=").append(buildCallbackURL);
				 response.sendRedirect(url.toString());
			}
		}catch(Exception e){
			 //跳转至sso认证中心
			 StringBuilder url = new StringBuilder();
			 url.append(SSO_SERVER_URL).append("?callbackURL=").append(buildCallbackURL);
			 response.sendRedirect(url.toString());
		}
	}



	public void destroy() {
		// TODO Auto-generated method stub

	}

}
